package com.example.xupdateLearningProject;

import android.app.Application;

import com.example.xupdateLearningProject.http.OKHttpUpdateHttpService;
import com.xuexiang.xaop.XAOP;
import com.xuexiang.xaop.util.PermissionUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.XHttpSDK;
import com.xuexiang.xpage.PageConfig;
import com.xuexiang.xpage.core.PageOption;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.entity.UpdateError;
import com.xuexiang.xupdate.listener.OnUpdateFailureListener;
import com.xuexiang.xupdate.utils.UpdateUtils;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        XUtil.init(this);
        PageConfig.getInstance()
                .debug("PageLog")
                .init(this);
        XAOP.init(this);
        XAOP.debug(true);
        XAOP.setOnPermissionDeniedListener(new PermissionUtils.OnPermissionDeniedListener() {
            @Override
            public void onDenied(List<String> permissionsDenied) {
                ToastUtils.toast("权限申请被拒绝:" + StringUtils.listToString(permissionsDenied,","));
            }
        });
        initXHttp();
        initOKHttpUtils();
        initUpdate();
    }

    private void initUpdate(){
        XUpdate.get()
                .debug(true)
                .isWifiOnly(false)
                .isGet(true)
                .isAutoMode(false)
                .param("versionCode", UpdateUtils.getVersionCode(this))
                .param("appKey",getPackageName())
                .setOnUpdateFailureListener(new OnUpdateFailureListener() {
                    @Override
                    public void onFailure(UpdateError error) {
                        error.printStackTrace();
                        if (error.getCode() != UpdateError.ERROR.CHECK_NO_NEW_VERSION) {
                            ToastUtils.toast(error.toString());
                        }
                    }
                })
                .supportSilentInstall(false)
                .setIUpdateHttpService(new OKHttpUpdateHttpService())
                .init(this);
    }

    private void initOKHttpUtils(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(20000l, TimeUnit.MILLISECONDS)
                .readTimeout(20000l,TimeUnit.MILLISECONDS)
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }

    private void initXHttp(){
        XHttpSDK.init(this);
        XHttpSDK.debug("XHTTP");
        XHttp.getInstance().setTimeout(2000);
    }
}
